package service

import (
	"context"
	"discount-service/basic/config"
	__ "discount-service/basic/proto"
	"discount-service/model"
	"discount-service/pkg"
	"errors"
)

type Server struct {
	__.UnimplementedDiscountServer
}

// UserLogin 登录
func (s *Server) UserLogin(_ context.Context, in *__.UserLoginReq) (*__.UserLoginResp, error) {
	users := model.Users{}
	config.DB.Where("phone = ?", in.Phone).First(&users)
	if users.ID == 0 {
		return nil, errors.New("用户不存在")
	}
	if pkg.Encryption(in.Password) != users.Password {
		return nil, errors.New("账号或者密码错误")
	}
	return &__.UserLoginResp{
		UserId: int64(users.ID),
	}, nil
}

// CreatedDiscount 发布
func (s *Server) CreatedDiscount(_ context.Context, in *__.CreatedDiscountReq) (*__.CreatedDiscountResp, error) {
	coupons := model.Coupons{
		UserId:        in.UserId,
		Name:          in.Name,
		IsLimitPut:    in.IsLimitPut,
		PutCount:      in.PutCount,
		UseCouponType: in.UseCouponType,
		StartTime:     in.StartTime,
		EndTime:       in.EndTime,
		DayNum:        in.DayNum,
		CouponType:    in.CouponType,
		Money:         float64(in.Money),
		SpendMony:     float64(in.SpendMony),
		Discount:      in.Discount,
		TotalMoney:    float64(in.TotalMoney),
		UseGoodsType:  in.UseGoodsType,
		PromotionWay:  in.PromotionWay,
		GetType:       in.GetType,
		LimitCount:    in.LimitCount,
	}
	config.DB.Create(&coupons)
	return &__.CreatedDiscountResp{
		Message: "发布成功",
	}, nil
}

// DiscountList 列表
func (s *Server) DiscountList(_ context.Context, in *__.DiscountListReq) (*__.DiscountListResp, error) {
	var coupons []model.Coupons
	page := in.Page

	if page <= 0 {
		page = 1
	}
	sizePage := in.SizePage

	switch {
	case sizePage > 100:
		sizePage = 100
	case sizePage <= 0:
		sizePage = 10
	}

	config.DB.Model(&coupons).Find(&coupons)
	var list []*__.GetByList
	offset := (page - 1) * sizePage
	config.DB.Offset(int(offset)).Limit(int(sizePage)).Order("created_at desc").Find(&list)
	for _, v := range coupons {
		byList := __.GetByList{
			Name:          v.Name,
			UseCouponType: v.UseCouponType,
			StartTime:     v.StartTime,
			CouponType:    v.CouponType,
			GetType:       v.GetType,
			LimitCount:    v.LimitCount,
			Status:        v.Status,
		}
		list = append(list, &byList)
	}
	return &__.DiscountListResp{
		List: list,
	}, nil
}

// DiscountDel 删除
func (s *Server) DiscountDel(_ context.Context, in *__.DiscountDelReq) (*__.DiscountDelResp, error) {
	var coupons model.Coupons

	config.DB.Where("id = ?", in.DiscountId).First(&coupons)
	if coupons.ID == 0 {
		return nil, errors.New("优惠卷不存在")
	}
	config.DB.Delete(&coupons)
	return &__.DiscountDelResp{
		Message: "删除成功",
	}, nil
}
